package com.sise.thread.lab01.lab02;

class ThreadTrainl implements Runnable{
    private int trainCount=100;
    public Object obj=new Object();

    //局部变量不会受到线程安全问题的影响
    @Override
    public void run() {
        while (trainCount>0){
            try{
                Thread.sleep(50);
            }catch (Exception e){
            }
            sale();
        }
    }


    private void sale() {
        //同步代码块 ---走到这个位置的时候，可能会有多个线程进行访问，谁先拿到锁谁就先进行购票
            synchronized (obj) {
                if (trainCount > 0) {
                    System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
                }
                trainCount--;
            }
        }
    }

//模拟火车站抢票
public class ThreadMain {
    public static void main(String[] args) {
        //为了模拟有两个窗口在抢票
        ThreadTrainl threadTrainl=new ThreadTrainl();
        Thread t1= new Thread(threadTrainl,"窗口1");
        Thread t2= new Thread(threadTrainl,"窗口2");
        t1.start();
        t2.start();
    }
}
